package com.hornsun.client.api;

import com.hornsun.config.ConfigInfo;
import com.hornsun.data.constant.error.AccountError;
import com.hornsun.data.constant.error.CommonError;
import com.hornsun.data.dbo.Client;
import com.hornsun.data.dto.WebClientDTO;
import com.hornsun.data.repository.ClientRepository;
import com.hornsun.data.repository.OrganizationRepository;
import com.hornsun.data.repository.RoleRepository;
import com.hornsun.data.repository.mapper.ClientDTOMapper;
import com.hornsun.util.DESUtil;
import com.hornsun.util.RSAUtils;
import com.hornsun.util.UploadImgUtil;
import com.hornsun.client.dto.PersonalInfo;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by 编译中... on 2018/7/13.
 */
@RestController
@RequestMapping("/api/client")
public class ClientAPI {
    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private OrganizationRepository organizationRepository;
    @Autowired
    private ClientDTOMapper clientDTOMapper;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ConfigInfo configInfo;

    //通过部门获取用户
    @GetMapping("/getByDepartment")
    public ResponseEntity<?> getByDepartment(@RequestParam("id")int id){
        return new ResponseEntity<Object>(clientRepository.getByDepartment(id), HttpStatus.OK);
    }

    @GetMapping("/getByGuid")
    public ResponseEntity<?> getByGuid(@RequestParam("guid")String clientGuid){
        WebClientDTO webClientDTO = clientDTOMapper.getByGuid(clientGuid);
        if (webClientDTO==null){
            return new ResponseEntity<Object>(CommonError.NOT_EXIST.getCode(),HttpStatus.OK);
        }
        return new ResponseEntity<Object>(webClientDTO,HttpStatus.OK);
    }

    //通过部门和角色获取用户
    @GetMapping("/getByDepartmentAndRole")
    public ResponseEntity<?> getByDepartmentAndRole(@RequestParam("id")Integer id,@RequestParam("role")String roleGuid){
        return new ResponseEntity<Object>(clientRepository.getByRoleAndDepartment(roleGuid,id),HttpStatus.OK);
    }

    //获取个人信息
    @GetMapping("/getPersonalInfo")
    public ResponseEntity<?> getPersonalInfo(HttpSession httpSession){
        String account = (String) httpSession.getAttribute("Account");
        Client client = clientRepository.getByAccount(account);
        if (client==null){
            return new ResponseEntity<Object>(null,HttpStatus.OK);
        }
        PersonalInfo personalInfo = new PersonalInfo();
        personalInfo.setAccount(client.getAccount());
        personalInfo.setName(client.getName());
        personalInfo.seteMail(client.geteMail());
        personalInfo.setPortrait(client.getPortrait());
        personalInfo.setPhone(client.getPhone());
        if (organizationRepository.getById(client.getDepartmentId())!=null){
            String department = organizationRepository.getById(client.getDepartmentId()).getOrganizationName();
            personalInfo.setDepartment(department);
        }else {
            personalInfo.setDepartment("");
        }
        if (roleRepository.getByGuid(client.getRoleGuid())!=null){
            personalInfo.setRole(roleRepository.getByGuid(client.getRoleGuid()).getRoleName());
        }else {
            personalInfo.setRole("");
        }
        return new ResponseEntity<Object>(personalInfo,HttpStatus.OK);
    }



    //修改用户密码
    @PostMapping("/updatePassword")
    public ResponseEntity<?> updatePassword(HttpSession httpSession,
                                            @RequestParam("pwd")String pwd,
                                            @RequestParam("newPwd")String newPwd,
                                            @RequestParam("pwdAgain")String pwdAgain) throws Exception {
        if (pwd==null||pwd.isEmpty()||newPwd==null||newPwd.isEmpty()||pwdAgain==null||pwdAgain.isEmpty()){
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        String decryptPwd = new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(newPwd.replace("%2B","+")),RSAUtils.getPrivateKey()));
        String regex ="^[a-zA-Z\\d]{6,16}$";

        if (!decryptPwd.matches(regex)){
            return new ResponseEntity<Object>(AccountError.PASSWORD_FORMAT_ERROR.getCode(),HttpStatus.OK);
        }
        if (!pwdWhetherSame(newPwd,pwdAgain)){
            return new ResponseEntity<Object>(AccountError.TWO_PASSWORD_DIFFERENT.getCode(),HttpStatus.OK);
        }
        if (decryptPwd.equals(configInfo.getInitialPassword())){
            return new ResponseEntity<Object>(AccountError.INIT_PASSWORD.getCode(),HttpStatus.OK);
        }
        String account = (String) httpSession.getAttribute("Account");
        Client client = clientRepository.getByAccount(account);
        String password  =DESUtil.encrypt(decryptPwd);
        if (password.equals(client.getPassword())){
            return new ResponseEntity<Object>(AccountError.SAME_WITH_OLD.getCode(),HttpStatus.OK);
        }
        String oldPassword  = DESUtil.encrypt(new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(pwd.replace("%2B","+")),RSAUtils.getPrivateKey())));
        if (clientRepository.checkAccountInfo(account,oldPassword)){
            client.setPassword(password);
            clientRepository.updateClient(client);
            return new ResponseEntity<Object>(HttpStatus.OK);
        }else {
            return new ResponseEntity<Object>(AccountError.OLD_PASSWORD_ERROR.getCode(),HttpStatus.OK);
        }
    }


    /**
     * 更换头像
     * @param file
     * @return
     */
    @Transactional
    @PostMapping("/updatePortrait")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file,
                                         HttpServletRequest request,
                                         HttpSession httpSession){
        String account = (String) httpSession.getAttribute("Account");
        Client client = clientRepository.getByAccount(account);
        if (client==null){
            return new ResponseEntity<Object>("该账户不存在！",HttpStatus.OK);
        }
        String guid = UploadImgUtil.uploadImage(file);
        String imgName = guid+"small.jpg";
        String path = "http://"+request.getLocalAddr()+":"+request.getLocalPort()+"/img/"+imgName;
        client.setPortrait(path);
        clientRepository.updateClient(client);
        return new ResponseEntity<Object>(path,HttpStatus.OK);
    }

    /**
     * 重置用户密码
     * @param clientGuid
     * @return
     */
    @PostMapping("/permission/resetPassword")
    public ResponseEntity<?> resetPassword(@RequestParam("guid")String clientGuid) throws Exception {
        if (clientGuid==null||clientGuid.isEmpty()){
            return new ResponseEntity<Object>(CommonError.BAD_PARAM.getCode(),HttpStatus.OK);
        }
        Client client = new Client();
        client.setClientGuid(clientGuid);
        client.setPassword(DESUtil.encrypt(configInfo.getInitialPassword()));
        clientRepository.updateClient(client);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }


    @GetMapping("/getPermission")
    public ResponseEntity<?> getPermission(){
        return new ResponseEntity<Object>(HttpStatus.OK);
    }



    public static boolean pwdWhetherSame(String pwd,String pwdAgain) throws Exception {
        String password = new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(pwd.replace("%2B","+")),RSAUtils.getPrivateKey()));
        String passwordAgain = new String(RSAUtils.decryptByPrivateKey(Base64.decodeBase64(pwdAgain.replace("%2B","+")),RSAUtils.getPrivateKey()));
        return password.equals(passwordAgain);
    }


}
